# -*- coding:UTF-8 -*-
import MySQLdb
import MySQLdb.cursors

class ConnMySql:
    def __init__(self, host, port, name, user, password, charset):
        if name is None:
            self._dbname = null
        else:
            self._dbname = name
        if host is None:
            self._dbhost = null
        else:
            self._dbhost = host

        self._dbport = int(port)
        self._dbuser = user
        self._dbpassword = password
        self._dbcharset = charset

        self._conn = self.connMySQL()

        if (self._conn):
            self._cursor = self._conn.cursor()

    # 连接
    def connMySQL(self):
        conn = False
        try:
            conn = MySQLdb.connect(host=self._dbhost,
                                   user=self._dbuser,
                                   passwd=self._dbpassword,
                                   db=self._dbname,
                                   port=self._dbport,
                                   cursorclass=MySQLdb.cursors.DictCursor,
                                   charset=self._dbcharset)
        except Exception, data:
            conn = False
        return conn

    # 查询
    def fetch_all(self, sql):
        res = False
        if (self._conn):
            try:
                self._cursor.execute(sql)
                res = self._cursor.fetchall()
            except Exception, data:
                res = False
        return res

    # 增加
    def insert(self, sql):
        flag = False
        if (self._conn):
            try:
                self._cursor.execute(sql)
                # self._conn.commit()
                flag = True
            except Exception, data:
                flag = False
        return flag

    # 更新
    def update(self, sql):
        flag = False
        if (self._conn):
            try:
                self._cursor.execute(sql)
                # self._conn.commit()
                flag = True
            except Exception, data:
                flag = False
        return flag

    def commit(self):
        flag = False
        if(self._conn):
            try:
                self._conn.commit()
                flag = True
            except Exception, data:
                flag = False

    # 关闭
    def close(self):
        flag = False
        if (self._conn):
            try:
                if (type(self._cursor) == 'object'):
                    self._cursor.close()
                if (type(self._conn) == 'object'):
                    self._conn.close()
                    flag = True
            except Exception, data:
                flag = False